var express = require('express');
var router = express.Router();
var connection = require('../mysql/mysql');

//七牛上传
const qiniu = require("qiniu");

let accessKey = 'yfUXBqtIcXVc32zQByJ4lB3q7Rt722gx6Mf6vnIQ';
let secretKey = 'TkBjn5HfGw1MdPb5mWnJIHuupbP4CcDIxXsnhVC6';
let bucket = "d1025ok";
const url = "http://q8g5m4j2v.bkt.clouddn.com"; //创建bucket是七牛自动分配的域名
qiniu.conf.ACCESS_KEY = accessKey;
qiniu.conf.SECRET_KEY = secretKey;
let mac = new qiniu.auth.digest.Mac(accessKey, secretKey);
let config = new qiniu.conf.Config();
config.zone = qiniu.zone.Zone_z0;
let bucketManager = new qiniu.rs.BucketManager(mac, config);

/* 获取七牛token */
router.get('/getQiNiuToken', function (req, res, next) {
  let options = {
    scope: bucket //七牛资源目录
  };
  let putPolicy = new qiniu.rs.PutPolicy(options);
  let uploadToken = putPolicy.uploadToken(mac);

  return res.json({
    code: 0,
    data: {token: uploadToken},
    success: true,
    message: '获取七牛token成功！',
  })
});

//获取七牛图片链接
router.get("/getImgUrl/:key", function (req, res, next) {
  if (!req.params.key) {
    return res.json({
      code: 1,
      data: null,
      success: false,
      message: "key不能为空",
    })
  }
  //生成下载链接url
  let downloadUrl = bucketManager.publicDownloadUrl(url, req.params.key);
  return res.json({
    code: 0,
    data: downloadUrl,
    success: true,
    message: '获取图片链接成功！',
  })
});

//删除七牛图片
router.get("/removeImg/:key", function (req, res, next) {
  if (!req.params.key) {
    return res.json({
      code: 1,
      data: null,
      success: false,
      message: "key不能为空",
    })
  }
  bucketManager.delete(bucket, req.params.key, function (err, respBody, respInfo) {
    if (err) {
      console.log(err);
      //throw err;
    } else {
      console.log(respInfo.statusCode);
      console.log(respBody);
      return res.json({
        code: 0,
        data: null,
        success: true,
        message: '删除图片成功！',
      })
    }
  });
});

module.exports = router;
